import { Snowflake } from "api/structures/utils/Snowflake";
import { Http, HTTPRequest } from "api/client/http/Http"


type BasicCallback =  (error: Error | null, response: string | null) => void;

// https://discord.com/api/v9/channels/1013887582372900864/messages?before=1156294731748347964&limit=50
// https://discord.com/api/v9/channels/136891423655067648/messages?limit=50
// https://discord.com/api/v9/channels/215496276609990656/messages?after=1046278265427480668&limit=50
// https://discord.com/api/v9/channels/215496276609990656/messages?limit=50&around=1046256843623764078

/*
    {
        "op":14,
        "d":{
            "guild_id":"327414731654692866",
            "typing":true,
            "activities":true,
            "threads":true
        }
    }
*/

/*

    {
        "op":3,
        "d":{
            "status":"invisible",
            "since":0,
            "activities":[],
            "afk":true
        }
    }

*/


function getMessages(chat_id: string, query: string, callback: BasicCallback) {
    window.client.emit("debug", "Chat open " + chat_id)

    const request: HTTPRequest = {
        method: "GET",
        path: "https://discord.com/api/v9/channels/"+ chat_id +"/messages?limit=50" + query,
        headers: {
            "Authorization": window.client.token as string,
            // "Referer": "https://discord.com/channels/@me/219007907641950208"
        }
    }

    window.client.emit("debug", "request " + JSON.stringify(request))

    Http.request(request, function(err, data){

        if (err) {
            window.client.emit("debug", "Http request " + JSON.stringify(err))
            callback(err, null)
            return;
        }

        window.client.emit("debug", "Http request complete")
 
        callback(null, data as string)
    });
}

export function getBefore(chat_id: string, before: Snowflake, callback: BasicCallback) {
    getMessages(chat_id, "&before=" + before, callback)
}

export function getFrom(chat_id: string, callback: BasicCallback) {
    getMessages(chat_id, "", callback)
}

export function getAround(chat_id: string, around: Snowflake, callback: BasicCallback) {
    getMessages(chat_id, "&around=" + around, callback)
}

export function getAfter(chat_id: string, after: Snowflake, callback: BasicCallback) {
    getMessages(chat_id, "&after=" + after, callback)
}